import { Component, OnInit } from '@angular/core';
import { RequestService } from '../../services/request.service';
import { map, filter } from 'rxjs/operators';
@Component({
  selector: 'app-rx',
  templateUrl: './rx.component.html',
  styleUrls: ['./rx.component.css']
})
export class RxComponent implements OnInit {

  constructor(private request: RequestService) { }

  ngOnInit() {
    this.getPromise();
    this.getRx();
    //this.getRxs();
    this.getRxs2();
  }
  //  返回promise对象再then
  getPromise() {
    this.request.getPromise().then((data) => {
      console.log(data);
    }, (data) => {
      console.log(data);
    }).catch((err) => {
      console.log(err);
    });
  }
  // rxjs subscribe()
  getRx() {
    let disponable = this.request.getRx().subscribe((value) => console.log(value));
    // rxjs取消订阅
    setTimeout(() => {
      disponable.unsubscribe();
    }, 1000);
  }
  // rxjs可以多次执行
  getRxs() {
    this.request.getRxs().subscribe((value) => {console.log(value)});
  }
  getRxs2() {
    // pipe 可以处理返回的数据
    this.request.getRxs().pipe(filter((val: number) => {if (val % 2 === 0) {
      return true;
    }}), map(val => {
      return val * val;
    })).subscribe(value => console.log(value));
  }
}
